
// const fs = require('fs')
// const path = require('path')
// const express = require('express');
// const JsYaml = require('js-yaml')
// const mysql2 = require('mysql2/promise')
// const User = require('./user')
// const loggerMiddleware = require('./middleware/logger') // 日志中间件

import fs from 'fs'
import path from 'path'
import express from 'express'
import JsYaml from 'js-yaml'
import mysql2 from 'mysql2/promise'
import User from './user.js'
import loggerMiddleware from './middleware/logger.js'

import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const yaml = fs.readFileSync(path.resolve(__dirname, 'config', 'db.dev.yml'), 'utf8')
const config = JsYaml.load(yaml)

const sql = await mysql2.createConnection({
   ...config.db
})


const app = express() //express 是个函数
app.use((req,res,next)=>{ // 全部处理中间件
  // res.setHeader('Access-Control-Allow-Origin','http://localhost:80') //允许localhost 80 访问
  res.setHeader('Access-Control-Allow-Headers','Content-Type')
  res.setHeader('Access-Control-Allow-Methods','POST,GET,OPTIONS,DELETE,PUT,PATCH')
  next()
})
app.use('/assets', express.static(path.resolve(__dirname, 'static'))) // 静态资源中间件
app.use(express.json()) // 接收前端参数中间件
app.use(loggerMiddleware) // 挂载日志中间件
// localhost:/user/${routePath}
app.use('/user', User) // 挂载user模块

class Result { 
  constructor(code = 200, message = 'success', data = null) {
    this.code = code
    this.message = message
    this.data = data
  }
  static success(data) {
    return new Result(200, 'success', data)
  }
  static fail(message) {
    return new Result(500, message, null)
  }
  static notFound(message) {
    return new Result(404, message, null)
  }
  toJSON() {
    return this
  }
}
app.get('/', async (req, res) => {
  console.log('====req', req.query)
  res.set('custom-key', 'test') // 设置响应头属性
  const [data] = await sql.query('select * from user_tb')
  res.send(Result.success(data))
})
// sse
// app.get('/sse',(req,res)=>{
//   res.setHeader('Content-Type', 'text/event-stream')
//   res.status(200)
//   setInterval(() => {
//       res.write('event: test\n')
//       res.write('data: ' + new Date().getTime() + '\n\n')
//   }, 1000)
// })

app.post('/create', (req, res) => {
  res.send('post')
})
//如果是动态参数用 params
app.get('/query/:id', async (req, res) => {
  console.log(req.params)
  try {
    const [row] = await sql.query('select * from user_tb where user_id = ?', [req.params.id])
    res.json(Result.success(row[0]))
  } catch (error) {
    throw error
  }
})

app.listen(3000, () => console.log('Listening on port 3000'))